var Lib = {
  phoneRex: /^[1][3-9][0-9]{9}$/,
  smsCodeRex: /^[0-9]{6}$/,
  passWordRex: /^[0-9a-zA-Z]{6,20}$/,
  url: "http://www.cw.pub/aygj"
}

var sms = null
var smsCode = Vue.component('sms-code',{
  template: `<div class="sms-code">
      <mu-text-field :errorText="errorText" :placeholder="$t('forget.enterYZM')"  v-model="currentValue" fullWidth/>
      <mu-button flat  @click="getSMSCode" :disabled="canSend">{{codeMsg}}</mu-button>
  </div>`,
  mounted: function () {
    if (localStorage.SMSCodeStratTime) {
      this.sended = true;
      this.startTime = localStorage.SMSCodeStratTime;
      sms.sending();
    }
  },
   created: function () {
    sms = this;
  },
  methods:{
    getSMSCode(){
      sms.sended = true;
      sms.$emit('code')
      sms.startTime = new Date().getTime();
      localStorage.setItem('SMSCodeStratTime',sms.startTime);
      if(!sms.phone){
      	sms.sended = false;
      	return;
      }
      sms.sending()
    },
    sending(){
      let now = new Date().getTime();
      let time = Math.round((now - sms.startTime)/1000);
      sms.codeMsg = sms.$t('forget.shaodeng') +` ${sms.time - time} `+ sms.$t('forget.seconds');
      if(time>=sms.time){
        sms.sended = false;
        sms.startTime = null;
        sms.timer = null;
        sms.codeMsg = sms.$t('forget.getyzm')
        localStorage.removeItem('SMSCodeStratTime')
      }else{
        sms.timer = setTimeout(function(){
          sms.sending();
        },1000)
      }
    }
  },
  data () {
    return {
      codeMsg:this.$t('forget.getyzm'),
      sended:false,
      timer:null,
      startTime:null,
    }
  },
  props: {
    phone:{
      type:String,
      require:true,
    },
    time:{
      type:Number,
      require:true,
      default:60
    },
    value:{
      default:''
    },
    errorText:{
      default:''
    }
  },
  computed:{
    canSend(){
      return !(!sms.sended)
    },
    currentValue:{
      get(){
        return sms.value
      },
      set(val){
        return sms.$emit('input',val)
      }
    }
  },
  watch:{
    value:{
      handler:function(val,oldVal){
        sms.$emit('input',val);
      },
      deep:true
    },
  }
})
